package com.example.mq.mqserver.datacenter;

import com.example.mq.MqApplication;
import com.example.mq.mqserver.core.Exchange;
import com.example.mq.mqserver.core.ExchangeType;
import com.example.mq.mqserver.core.MSGQueue;
import com.example.mq.mqserver.core.Binding;
import com.example.mq.mqserver.mapper.MetaMapper;

import java.io.File;
import java.util.List;

/**
 * 通过这个类来封装针对数据库的操作.
 */
public class DataBaseManager {
    //从Spring中拿到线程的metaMapper
    private MetaMapper metaMapper;
    //对数据库进行初始化
    public void init() {
        //手动获取到MetaMapper

         this.metaMapper = MqApplication.context.getBean(MetaMapper.class);
                 // 构造数据库，如果数据库不存在
          if (!checkDBExists()) {
             // 1. 读取 sql ⽂件中的内容, 并创建表
             createTable();
             // 2. 插⼊默认数据
             createDefaultData();
             System.out.println("[DataBaseManager] 数据库初始化完成!");
            } else {
                System.out.println("[DataBaseManager] 数据库已经存在!");
            }
    }
    //查看数据库文件是否存在即可
    public boolean checkDBExists(){
        File file=new File("./data/meta.db");
        if(file.exists()){
            return true;
        }
        return false;

    }

    //建库操作不需要进行，首次执行数据库操作的时候会自动的创建meta.db文件夹（mybatis帮我们完成的）
    public void createTable(){
        metaMapper.createQueueTable();
        metaMapper.createBindingTable();
        metaMapper.createExchangeTable();
        System.out.println("[DataBaseManager] 创建表完成!");
    }

    //给数据库表中，添加默认的交换机
    //rabbitMQ有一个设定：带有一个匿名交换机，类型是DIRECT
    public void createDefaultData(){
        Exchange exchange = new Exchange();
        exchange.setName("");
        exchange.setType(ExchangeType.DIRECT);
        exchange.setDurable(true);
        exchange.setAutoDelete(false);
        metaMapper.insertExchange(exchange);
        System.out.println("[DataBaseManager] 创建初始数据完成!");
    }

    //其他数据库操作也封装一下
    public void insertExchage(Exchange exchange){
        metaMapper.insertExchange(exchange);

    }
    public void deleteExchange(String exchangeName) {
         metaMapper.deleteExchange(exchangeName);
    }

    public List<Exchange> selectAllExchanges() {
         return metaMapper.selectAllExchanges();
    }

    public void insertQueue(MSGQueue queue) {
         metaMapper.insertQueue(queue);
    }

    public void deleteQueue(String queueName) {
         metaMapper.deleteQueue(queueName);
    }

    public List<MSGQueue> selectAllQueues() {
         return metaMapper.selectAllQueues();
    }

    public void insertBinding(Binding binding) {
         metaMapper.insertBinding(binding);
    }

    public void deleteBinding(Binding binding) {
         metaMapper.deleteBinding(binding);
    }

    public List<Binding> selectAllBindings() {
         return metaMapper.selectAllBindings();
    }
}
